<?php
/**
 * 调查
 */
namespace app\admin\controller;
class Research extends base
{
    //前置方法
    protected $beforeActionList = [
        'map'  =>  ['only'=>'index'],
    ];

    /**
     * 搜索
     */
    protected function map(){
        if ($this->request->isGet()) {
            $data = $this->request->param();
            $this->datas = array();
            if (!empty($data['start_time']) && !empty($data['end_time']) && (strtotime($data['start_time']) < strtotime($data['end_time']))) {
                $this->datas ['create_time'] = [
                    ['>', strtotime($data['start_time'])],
                    ['<', strtotime($data['end_time'])]
                ];
            }
            if (!empty($data['cid'])) {
                $this->datas ['cid'] = $data['cid'];
            }
            if (!empty($data['title'])) {
                $this->datas ['title'] = ['like', '%' . $data['title'] . '%'];
            }
            $this->datas['lang'] = cookie('think_var_admin');
        }
    }


    public function add(){
        $ss = allow_release_arctype(0, array($this->request->controller()));
        $this->assign('ss', $ss);
        return $this->fetch('add',
            ['addcid' => $this->request->param('addcid'),]
        );
    }

    public function edit($id)
    {

        if (intval($id) < 1) {
            $this->error('数据错误');
        }
        //清理缓存
        cache($this->request->controller().$id,null);
        $data = $this->model->get($id);
        $data['starttime'] = date("Y-m-d H:i:s", $data['starttime']);
        $data['dateline'] = date("Y-m-d H:i:s", $data['dateline']);
        $rqdata = db('Research_question')->where(array('rid' => $id))->order('id asc')->select();
        $useqids = $list = array();
        foreach ($rqdata as $v) {
            $useqids[] = $v['id'];
            $answerobj = db('Research_answer')->where(array('qid' => $v['id']))->order('id asc')->select();
            $v['answer'] = $answerobj;
            $list[] = $v;
        }

        $ss = allow_release_arctype(0, array($this->request->controller()));
        $this->assign('ss', $ss);

        $this->assign('list', $list);
        $this->assign('data', $data);
        return $this->fetch();
    }

    public function count($id)
    {
        $aa = array();
        $an = db('research_result')->where('rid',$id)->select();
        foreach ($an as $k => $value) {
            $answer = json_decode($value['content']);
            if(empty($answer))continue;
            foreach ($answer as $ki => $va) {
                $aa[$k][$ki]['question'] = db('research_question')->where(array('id' => $ki))->value('name');
                $aa[$k][$ki]['answer'] = $va;
            }
        }

        $question = db('Research_question')->where(array('rid' => $id))->order('id asc')->select();
        $list = array();
        foreach ($question as $q) {
            $q['answer'] = db('Research_answer')->where(array('qid' => $q['id']))->order('id asc')->select();
            $q['rowspan'] = count($q['answer']);
            $list[] = $q;
        }

        $this->assign([
            'list'=> $list,
            'aa'=> $aa,
            ]);

        return $this->fetch();
    }


    /**
     * 保存
     */
    public function save()
    {
        if (!$this->request->isPost()) {
            return ajax_info('请求失败');
        }
        $useqids=$useaids=$updateqids=$updateaids=$nouseaid=$nouseqid=array();

        $data = $this->request->post();
        if(empty($data['cid'])||empty($data['title'])){
            return ajax_info('请填写标题');
            exit();
        }

        if(empty($data['question'])||empty($data['option'])){
            return ajax_info('请填写问题的题目');
            exit();
        }

        $question = isset($data['question']) ? $data['question'] : array();
        $option = isset($data['option']) ? $data['option'] : array();
        $rid = isset($data['id']) ? intval($data['id']) : 0;
        $ismulti = isset($data['ismulti']) ? $data['ismulti'] : array();
        $qids = isset($data['qid']) ? $data['qid'] : array();
        $aids = isset($data['oid']) ? $data['oid'] : array();
        $data['starttime'] = strtotime($data['starttime']);
        $data['dateline'] = strtotime($data['dateline']);

        if(!empty($data['id'])){

                $rqdata = db('Research_question')->where(array('rid' => $rid))->order('id asc')->select();
                foreach ($rqdata as $v) {
                    $useqids[] = $v['id'];
                    $answerobj = db('Research_answer')->where(array('qid' => $v['id']))->order('id asc')->select();
                    $v['answer'] = $answerobj;
                    foreach ($answerobj as $a) {
                        $useaids[] = $a['id'];
                    }
                }

            $this->model->allowField(true)->save($data, ['id' =>$rid]);

            //删除的题目
            foreach ($qids as $k => $v) {
                $updateqids[] = $qids[$k];
            }

            foreach ($question as $k => $q) {
                    if (!isset($option[$k]) || (isset($option[$k]) && empty($option[$k])) || empty($q) || !isset($k)) continue;
                    $qdata = array('rid' => $rid, 'name' => htmlspecialchars($q), 'type' => isset($ismulti[$k]) ? intval($ismulti[$k]) : 0);
                    if ($qids[$k]) {
                         $qdata['id'] = $qids[$k];
                        db('Research_question')->update($qdata);
                        foreach ($option[$k] as $i => $v) {
                            if (!isset($aids[$k][$i])) continue;
                            $adata = array('qid' => $qids[$k], 'name' => htmlspecialchars($v));
                            if (empty($aids[$k][$i])) {
                                db('Research_answer')->insert($adata);
                            } else {
                                $adata['id'] = $aids[$k][$i];
                                db('Research_answer')->update($adata);
                                $updateaids[] = $aids[$k][$i];
                            }
                        }
                    } else {
                        if (db('Research_question')->insert($qdata)) {
                            $qid =db('Research_question')->getLastInsID();
                            foreach ($option[$k] as $v) {
                                if (empty($v)) continue;
                                $adata = array('qid' => $qid, 'name' => htmlspecialchars($v));
                                $aid = db('Research_answer')->insert($adata);
                            }
                        }
                    }
                }
                $nouseqid = array_diff($useqids, $updateqids);

                if ($nouseqid) {
                    db('Research_question')->where(array('id' => array('in', $nouseqid)))->delete();
                }

                 $nouseaid = array_diff($useaids, $updateaids);

            if ($nouseaid) {
                    db('Research_answer')->where(array('id' => array('in', $nouseaid)))->delete();
                }
                return ajax_info('修改成功！' ,'u');

        }

        $data['lang']=cookie('think_var_admin');
        $res = $this->model->allowField(true)->save($data);
        if ($res) {
            $rid =$this->model->id;

            foreach ($question as $k => $q) {
                if (!isset($option[$k]) || (isset($option[$k]) && empty($option[$k])) || empty($q)) continue;
                $qdata = array('rid' => $rid, 'name' => htmlspecialchars($q), 'type' => isset($ismulti[$k]) ? intval($ismulti[$k]) : 0);
                if ( db('Research_question')->insert($qdata)) {
                    $qid =db('Research_question')->getLastInsID();
                    foreach ($option[$k] as $v) {
                        if (empty($v)) continue;
                        $adata = array('qid' => $qid, 'name' => htmlspecialchars($v));
                        $aid = db('Research_answer')->insert($adata);
                    }
                }
            }

            return ajax_info('保存成功','y');
        } else {
            return ajax_info('添加失败');
        }
    }

    /**
     * 删除
     */
    public function del($id)
    {
            $re = $this->model->del($id);
            if ($re) {
                $this->_delcahe();
                $rqdata = db('Research_question')->where(array('rid' => $id))->select();
                $useqids = $useaids = array();
                foreach ($rqdata as $v) {
                    $useqids[] = $v['id'];
                    $answerobj = db('Research_answer')->where(array('qid' => $v['id']))->order('id asc')->select();
                    foreach ($answerobj as $a) {
                        $useaids[] = $a['id'];
                    }
                }
                if ($useqids) {
                    db('Research_question')->where(array('id' => array('in', $useqids)))->delete();
                }
                if ($useaids) {
                    db('Research_answer')->where(array('id' => array('in', $useaids)))->delete();
                }
                ajaxMsg('1', '删除成功');
            } else {
                ajaxMsg('0', '删除成功');

            }

    }
}
